package com.ctshk.rpc.scenic.service.impl.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ctshk.common.constant.ElasticSearchConstant;
import com.ctshk.common.constant.RedisConstants;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.ChannelMainData;
import com.ctshk.common.enums.Currency;
import com.ctshk.common.enums.SystemBusinessType;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.scenic.constant.ScenicProductConstants;
import com.ctshk.rpc.scenic.dto.ScenicProductChannelOnlineSelfPlatformDTO;
import com.ctshk.rpc.scenic.dto.ScenicResourceDetailDTO;
import com.ctshk.rpc.scenic.dto.app.ScenicProductEsDTO;
import com.ctshk.rpc.scenic.dto.app.ScenicProductEsDetailDTO;
import com.ctshk.rpc.scenic.dto.app.ScenicProductEsInfoDTO;
import com.ctshk.rpc.scenic.dto.app.ScenicProductEsListDTO;
import com.ctshk.rpc.scenic.dto.app.inner.*;
import com.ctshk.rpc.scenic.entity.ScenicProductCostStrategySpecStock;
import com.ctshk.rpc.scenic.mapper.ScenicProductChannelOnlineSelfPlatformMapper;
import com.ctshk.rpc.scenic.mapper.ScenicProductCostStrategySpecStockMapper;
import com.ctshk.rpc.scenic.req.app.ScenicProductEsListReq;
import com.ctshk.rpc.scenic.req.app.ScenicProductEsReq;
import com.ctshk.rpc.scenic.service.IScenicProductService;
import com.ctshk.rpc.scenic.service.IScenicResourceService;
import com.ctshk.rpc.scenic.service.app.IScenicTicketEsSearchService;
import com.ctshk.rpc.system.dto.ScenicDTO;
import com.ctshk.rpc.system.req.ScenicDetailReq;
import com.ctshk.rpc.system.service.ISceneService;
import com.ctshk.rpc.user.req.UserFootPointReq;
import com.ctshk.rpc.user.service.IUserFootPointService;
import com.github.houbb.heaven.util.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@DubboService
public class ScenicTicketEsSearchServiceImpl implements IScenicTicketEsSearchService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ScenicTicketEsSearchServiceImpl.class);
    private static final String videoTypes = "mp4,wmv,rmvb,";
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Autowired
    IScenicProductService iScenicProductService;
    @Autowired
    ScenicProductCostStrategySpecStockMapper scenicProductCostStrategySpecStockMapper;
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @DubboReference
    private IUserFootPointService userFootPointService;
    @DubboReference
    private ISceneService iSceneService;
    @Autowired
    ScenicProductChannelOnlineSelfPlatformMapper scenicProductChannelOnlineSelfPlatformMapper;
    @Autowired
    IScenicResourceService iScenicResourceService;

    /**
     * 查询门票列表ES
     * @param scenicProductEsListReq
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Result<PageResponse<ScenicTicketListDTO>> selectScenicEsTicketList(ScenicProductEsListReq scenicProductEsListReq, Integer pageNum, Integer pageSize) {
        SearchRequest searchRequest = new SearchRequest(ElasticSearchConstant.SCENIC);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        Long channelIdAttr = scenicProductEsListReq.getChannelId();
        {// 添加搜索条件
            /*if(scenicProductEsListReq.getChannelId() != null) {
                if (!scenicProductEsListReq.getChannelId().equals(ChannelMainData.APP_H5.getId())) {
                    channelIdAttr = scenicProductEsListReq.getChannelId();
                    //scenicProductEsListReq.setChannelId(ChannelMainData.APP_H5.getId());
                }
            }*/

            // 必须匹配 渠道ID， 城市ID， 非删除状态， 上架
            boolQueryBuilder.filter( QueryBuilders.fuzzyQuery("channelId", String.valueOf(scenicProductEsListReq.getChannelId())) );
            boolQueryBuilder.filter( QueryBuilders.fuzzyQuery("cityId", scenicProductEsListReq.getCityId()) );
            boolQueryBuilder.filter( QueryBuilders.fuzzyQuery("isDeleted", 0) );
            boolQueryBuilder.filter( QueryBuilders.fuzzyQuery("status", 1) );
            if(null != scenicProductEsListReq.getProductTypeName() && !scenicProductEsListReq.getProductTypeName().equals("全部")){
                boolQueryBuilder.filter( QueryBuilders.termQuery("productTypeName.keyword", scenicProductEsListReq.getProductTypeName()) );
            }

            // 模糊匹配
            if(StringUtils.isNotBlank(scenicProductEsListReq.getName())){
                // 产品名称
                boolQueryBuilder.filter( QueryBuilders.wildcardQuery("productName", "*" + scenicProductEsListReq.getName() + "*") );
            }
            if(scenicProductEsListReq.getThemes() != null && !scenicProductEsListReq.getThemes().equals("")){
                // 主题
                String[] split = scenicProductEsListReq.getThemes().split(",");
                for (String themeName : split) {
                    boolQueryBuilder.filter(QueryBuilders.wildcardQuery("themeJson", themeName));
                }
            }

            // 选择匹配
            if(scenicProductEsListReq.getIsRecommend() != null){
                // 是否推荐
                boolQueryBuilder.filter( QueryBuilders.matchQuery("isRecommend", scenicProductEsListReq.getIsRecommend()) );
            }
        }
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        searchSourceBuilder.from((pageNum-1)*pageSize);
        searchSourceBuilder.size(pageSize);

        ScenicProductEsListDTO scenicProductEsListDTO = new ScenicProductEsListDTO();

        try{
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            if(search != null){
                List<ScenicTicketList> scenicTicketLists = new ArrayList<>();
                SearchHits hits = search.getHits();
                long totalHits = hits.getTotalHits().value;
                for (SearchHit hit : hits) {
                    ScenicTicketList scenicTicketList = JSON.parseObject(hit.getSourceAsString(), ScenicTicketList.class);
                    // 过滤没有主题的
                    if(scenicTicketList.getThemeJson() == null || scenicTicketList.getThemeJson().trim().equals("")){
                        continue;
                    }
                    scenicTicketLists.add(scenicTicketList);
                }
                Set<String> themeList = new HashSet<>();
                // 进行主题分类
                for (ScenicTicketList scenicTicketList : scenicTicketLists) {
                    List<String> themes = JSON.parseArray(scenicTicketList.getThemeJson(), String.class);
                    for (String theme : themes) {
                        themeList.add(theme);
                    }
                }
                scenicProductEsListDTO.setThemeList(themeList);
                List<ScenicTicketListDTO> scenicTicketListDTOS = new ArrayList<>();
                for (ScenicTicketList scenicTicketList : scenicTicketLists) {
                    ScenicTicketListDTO scenicTicketListDTO = new ScenicTicketListDTO();
                    scenicTicketListDTO.setProductId(scenicTicketList.getProductId());
                    scenicTicketListDTO.setTitle(scenicTicketList.getProductName());
                    ScenicProductEsDTO spe = EntityUtil.copy(scenicTicketList,ScenicProductEsDTO.class);

                    //BigDecimal rate = null;
                    List<ScenicProductCostStrategySpecStock> stocksObj = scenicProductCostStrategySpecStockMapper.quertCostPriceByid(scenicTicketList.getProductId());
                    if (!Objects.isNull(stocksObj.get(0).getCostPrice())){
                        //获取成本价格
                        scenicTicketListDTO.setPrice(stocksObj.get(0).getCostPrice());
                        //rate = stocksObj.get(0).getCostPrice();
                        spe.setCostPrice(stocksObj.get(0).getCostPrice());
                        scenicTicketListDTO.setCostAmount(stocksObj.get(0).getCostPrice());
                    }

                    BigDecimal amountObj = null;
                    if (null != channelIdAttr){
                        ScenicProductChannelOnlineSelfPlatformDTO platformObj = new ScenicProductChannelOnlineSelfPlatformDTO();
                        //获取加服，计算总价
                        platformObj = scenicProductChannelOnlineSelfPlatformMapper.selectByProductId(scenicTicketList.getProductId() , channelIdAttr);
                        if (!Objects.isNull(platformObj)){
                            //加服价格
                            amountObj = platformObj.getAmount();
                            spe.setAdjustType(platformObj.getAdjustType());
                            spe.setAmount(amountObj);
                            scenicTicketListDTO.setAmount(amountObj);
                        }
                    }
                    computeScenicPriceTicketList(spe);// 计算价格

                    scenicTicketListDTO.setExchangeRate(spe.getExchangeRate());
                    scenicTicketListDTO.setReserveCharge(spe.getReserveCharge());

                    scenicTicketListDTO.setMoney(spe.getCostPrice());
                    scenicTicketListDTO.setPrice(spe.getCostPrice());
                    scenicTicketListDTO.setChannelId(scenicTicketList.getChannelId());
                    scenicTicketListDTO.setScenicLocation(scenicTicketList.getScenicLocation());
                    // 解析图片
                    String photosJson = scenicTicketList.getPhotosJson();
                    if(photosJson != null){
                        List<JSONObject> jsonObjects = JSON.parseArray(photosJson, JSONObject.class);
                        for (JSONObject jsonObject : jsonObjects) {
                            String url = (String) jsonObject.get("url");
                            if(url != null){
                                scenicTicketListDTO.setPng(url);
                                break;
                            }
                        }
                    }
                    {// 解析主题列表
                        String themeJson = scenicTicketList.getThemeJson();
                        if(themeJson != null && !themeJson.trim().equals("")){
                            List<String> themes = JSON.parseArray(themeJson, String.class);
                            List<TagListDTO> tagListDTOS = new ArrayList<>();
                            for (String theme : themes) {
                                TagListDTO tagListDTO = new TagListDTO();
                                tagListDTO.setName(theme);
                                tagListDTOS.add(tagListDTO);
                            }
                            scenicTicketListDTO.setThemeList(tagListDTOS);
                        }
                    }
                    scenicTicketListDTOS.add(scenicTicketListDTO);
                }
                PageResponse<ScenicTicketListDTO> scenicTicketListDTOPageResponse = new PageResponse<>();
                scenicTicketListDTOPageResponse.setRecords(scenicTicketListDTOS);
                scenicTicketListDTOPageResponse.setPageNo(pageNum);
                scenicTicketListDTOPageResponse.setPageSize(pageSize);
                scenicTicketListDTOPageResponse.setTotal(totalHits);
                scenicTicketListDTOPageResponse.setIsFirst(pageNum==0);
                scenicTicketListDTOPageResponse.setIsLast(pageSize*pageNum >= totalHits);
                return Result.success(scenicTicketListDTOPageResponse);
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.success(PageResponse.empty(pageNum));
        }
        return Result.success(PageResponse.empty(pageNum));
    }

    /**
     * 查询门票列表具体规格信息
     * @param channelId
     * @param productId
     * @param scenicId
     * @return
     */
    public Result<ScenicProductEsInfoDTO> selectScenicEsInfo(Long channelId, Long productId, Long scenicId, Long attrId) {
        ScenicProductEsDetailDTO scenicProductEsDetailDTO = selectScenicDetailAttrEs(channelId, productId, null, attrId);
        ScenicProductEsInfoDTO scenicProductEsInfoDTO = new ScenicProductEsInfoDTO();
        if(scenicProductEsDetailDTO != null){
            List<ScenicProductAttrListDTO> ticketList = scenicProductEsDetailDTO.getTicketList();
            if(ticketList != null && ticketList.size() > 0){
                for (ScenicProductAttrListDTO scenicProductAttrListDTO : ticketList) {
                    boolean have = false;
                    for (ProductAttrDTO productAttrDTO : scenicProductAttrListDTO.getItemList()) {
                        if(productAttrDTO.getId() != null && productAttrDTO.getId().equals(scenicId)){
                            have = true;
                            scenicProductEsInfoDTO.setProductName(scenicProductEsDetailDTO.getTitle());
                            scenicProductEsInfoDTO.setNeedInfo(scenicProductEsDetailDTO.getNeedInfo());
                            scenicProductEsInfoDTO.setScenicName(productAttrDTO.getTitle());
                            scenicProductEsInfoDTO.setReserveCharge(scenicProductEsDetailDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP));
                            //门票价格
                            //scenicProductEsInfoDTO.setTotalPrice(productAttrDTO.getPrice().subtract(scenicProductEsDetailDTO.getReserveCharge()));
                            scenicProductEsInfoDTO.setTotalPrice(productAttrDTO.getPrice());
                            scenicProductEsInfoDTO.setScenicLocation(scenicProductEsDetailDTO.getScenicLocation());
                            scenicProductEsInfoDTO.setLat(scenicProductEsDetailDTO.getLat());
                            scenicProductEsInfoDTO.setLon(scenicProductEsDetailDTO.getLon());
                            scenicProductEsInfoDTO.setCoverPhoto(scenicProductEsDetailDTO.getCoverPhoto());
                            scenicProductEsInfoDTO.setExchangeRateMoney(productAttrDTO.getExchangeRateMoney());

                            scenicProductEsInfoDTO.setValidType(scenicProductEsDetailDTO.getValidType());
                            scenicProductEsInfoDTO.setValidDay(scenicProductEsDetailDTO.getValidDay());
                            scenicProductEsInfoDTO.setValidDayBegin(scenicProductEsDetailDTO.getValidDayBegin());
                            scenicProductEsInfoDTO.setValidDayEnd(scenicProductEsDetailDTO.getValidDayEnd());
                            scenicProductEsInfoDTO.setAdmissionNotes(scenicProductEsDetailDTO.getAdmissionNotes());
                            scenicProductEsInfoDTO.setScenicPhotoJson(scenicProductEsDetailDTO.getScenicPhotoJson());
                            break;
                        }
                    }
                    if(have){
                        break;
                    }
                }
            }
        }
        return Result.success(scenicProductEsInfoDTO);
    }

    /**
     * 缓存更新
     *
     * @return
     */
    @Override
    public Result cacheUpdate(ScenicProductEsReq req) {
        log.info("【景点门票-更新ES缓存】开始");
        IndexRequest indexRequest = new IndexRequest(ElasticSearchConstant.SCENIC);
        indexRequest.id(String.valueOf(req.getProductId()));
        indexRequest.source(JSON.toJSONString(req), XContentType.JSON);
        try{
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        }catch (Exception e){
            log.info("【景点门票-更新ES缓存失败】");
            e.printStackTrace();
        }
        log.info("【景点门票-更新ES缓存】结束");
//
//        restHighLevelClient.index(updateRequest);
//        List<ScenicProductEsDTO> ScenicProductEsDTOs = buildLocalProductInfo(req);
//        upElasticSearch(localFunProductCacheUpDTOS,true);
//        upRedis(localFunProductCacheUpDTOS);
        return Result.success();
    }

    /**
     * @param req 景点门票产品id
     * @return
     */
    @Override
    public Result redisUpdate(ScenicProductEsReq req) {
        log.info("【景点门票-更新redis缓存】开始, data:{}", JSON.toJSONString(req));
        // 景点门票详情redis
        redisTemplate.opsForValue().set(RedisConstants.SCENIC_ORDER_DETAIL+req.getProductId(),JSON.toJSONString(req));
        log.info("【景点门票-更新redis缓存】结束");
        return Result.success();
    }




    @Override
    public Result<ScenicProductEsInfoDTO> selectScenicEsInfo(Long channelId, Long productId, Long scenicId) {
        return null;
    }


    /**
     * 查询门票详情ES
     * @param channelId
     * @param productId
     * @param userId
     * @return
     */
    public ScenicProductEsDetailDTO selectScenicDetailAttrEs(Long channelId, Long productId, Long userId, Long attrId) {
        ScenicProductEsDetailDTO scenicProductEsDetailDTO = new ScenicProductEsDetailDTO();
        SearchRequest searchRequest = new SearchRequest(ElasticSearchConstant.SCENIC);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        Long channelIdAttr = channelId;
        {// 过滤条件
            if(channelId != null){
                if (!channelId.equals(ChannelMainData.APP_H5.getId())) {
                    channelIdAttr = channelId;
                    channelId = ChannelMainData.APP_H5.getId();
                }
                boolQueryBuilder.filter( QueryBuilders.fuzzyQuery("channelId", String.valueOf(channelId)) );
            }
            boolQueryBuilder.filter( QueryBuilders.fuzzyQuery("productId", String.valueOf(productId)) );
        }
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = search.getHits();
            List<ScenicProductEsDTO> scenicProductEsDTOS = new ArrayList<>();
            List<ScenicProductAttrListDTO> scenicProductAttrListDTOS = new ArrayList<>();

            // 产品描述
            String productIntroduces = "";
            // 退订须知
            String admissionNotes = "";

            for (SearchHit hit : hits) {
                ScenicProductEsDTO scenicProductEsDTO = JSON.parseObject(hit.getSourceAsString(), ScenicProductEsDTO.class);
                if (null != channelIdAttr){
                    ScenicProductChannelOnlineSelfPlatformDTO platformObj = new ScenicProductChannelOnlineSelfPlatformDTO();
                    //计算总价

                    platformObj = scenicProductChannelOnlineSelfPlatformMapper.selectByProductId( productId , channelIdAttr);
                    if (!Objects.isNull(platformObj)){
                        //加服价格
                        scenicProductEsDTO.setAmount(platformObj.getAmount());
                    }
                }
                // 计算价格
                computeScenicPrice(scenicProductEsDTO);
                //computeScenicPriceTicketList(scenicProductEsDTO);
                // 设置价格
                scenicProductEsDetailDTO.setPrice(scenicProductEsDTO.getCostPrice());
                // 设置总价
                scenicProductEsDetailDTO.setMoney(scenicProductEsDTO.getCostPrice().setScale(0,BigDecimal.ROUND_UP)
                        .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                // 设置使用有效期
                scenicProductEsDetailDTO.setValidDay(scenicProductEsDTO.getValidDay());
                // 设置使用有效期类型
                scenicProductEsDetailDTO.setValidType(scenicProductEsDTO.getValidType());
                // 设置使用有效期
                scenicProductEsDetailDTO.setValidDayBegin(scenicProductEsDTO.getValidDayBegin());
                // 设置使用有效期
                scenicProductEsDetailDTO.setValidDayEnd(scenicProductEsDTO.getValidDayEnd());
                // 设置位置信息
                scenicProductEsDetailDTO.setScenicLocation(scenicProductEsDTO.getScenicLocation());
                scenicProductEsDetailDTO.setScenicPhotoJson(scenicProductEsDTO.getScenicPhotoJson());

                //获取scenicLocation景点地址
                scenicProductEsDetailDTO.setCoverPhoto(scenicProductEsDTO.getCoverImage());

                scenicProductEsDetailDTO.setLat(scenicProductEsDTO.getLat());
                scenicProductEsDetailDTO.setLon(scenicProductEsDTO.getLon());
                // 设置入园须知
                scenicProductEsDetailDTO.setAdmissionNotes(scenicProductEsDTO.getAdmissionNotes());
                scenicProductEsDetailDTO.setCityId(scenicProductEsDTO.getCityId());

                scenicProductEsDTOS.add(scenicProductEsDTO);
                productIntroduces = scenicProductEsDTO.getProductIntroduces();
                admissionNotes = scenicProductEsDTO.getAdmissionNotes();

                {
                    String attr2Name = scenicProductEsDTO.getAttr2Name()!=null?scenicProductEsDTO.getAttr2Name():"default";

                    ScenicProductAttrListDTO scenicProductAttrListDTO = new ScenicProductAttrListDTO();
                    scenicProductAttrListDTO.setId(scenicProductEsDTO.getProductId());
                    scenicProductAttrListDTO.setTitle(attr2Name);
                    List<ProductAttrDTO> productAttrDTOS = new ArrayList<>();



                    /*List<ScenicSpecStockDTO> scenicSpecStockList = new ArrayList<>();
                    List<ScenicProductCostStrategySpecStock>  scenicProductCostStrategySpecStock = scenicProductCostStrategySpecStockMapper.quertByid(productId);
                    for (ScenicProductCostStrategySpecStock specStockObj : scenicProductCostStrategySpecStock){
                        ScenicSpecStockDTO scenicSpecStockObj = new ScenicSpecStockDTO();
                        //门票及价格列表
                        scenicSpecStockObj.setAttr1Name(specStockObj.getAttr1Name());
                        scenicSpecStockObj.setAttr2Name(specStockObj.getAttr2Name());
                        scenicSpecStockObj.setId(specStockObj.getId());
                        scenicSpecStockObj.setStrategyId(specStockObj.getStrategyId());
                        scenicSpecStockObj.setProductId(specStockObj.getProductId());
                        scenicSpecStockObj.setCostPrice(specStockObj.getCostPrice());
                        scenicSpecStockObj.setMessage(scenicProductEsDTO.getCancelPolicy()==1? ScenicProductConstants.TIME_CANCEL : ScenicProductConstants.NOBACK_NOCANCEL);
                        //成本乘以倍数，加上服务费，加上加服
                        BigDecimal rate = specStockObj.getCostPrice();
                        Double price = scenicProductEsDTO.getExchangeRate();
                        BigDecimal mone = rate.multiply(BigDecimal.valueOf(price));
                        if (scenicProductEsDTO.getAmount() != null){
                            scenicSpecStockObj.setMoney(mone.setScale(0,BigDecimal.ROUND_UP)
                                    .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP))
                                    .add(scenicProductEsDTO.getAmount().setScale(0,BigDecimal.ROUND_UP)));
                        }else if (scenicProductEsDTO.getAmount() == null){
                            scenicSpecStockObj.setMoney(mone.setScale(0,BigDecimal.ROUND_UP)
                                    .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                        }
                        scenicSpecStockList.add(scenicSpecStockObj);
                        scenicProductAttrListDTO.setItemList(scenicSpecStockList);
                    }
                    scenicProductAttrListDTOS.add(scenicProductAttrListDTO);*/


                    // 门票信息
                    ProductAttrDTO productAttrDTO = new ProductAttrDTO();
                    if(scenicProductAttrListDTOS.size() == 0){
                        ScenicProductCostStrategySpecStock  specStockObj = scenicProductCostStrategySpecStockMapper.quertByattrid(attrId);
                            ProductAttrDTO productAttr = new ProductAttrDTO();
                            //门票及价格列表
                            productAttr.setAttr1Name(specStockObj.getAttr1Name());
                            productAttr.setAttr2Name(specStockObj.getAttr2Name());
                            productAttr.setId(scenicProductEsDTO.getAttrId());
                            productAttr.setStrategyId(specStockObj.getStrategyId());
                            productAttr.setProductId(specStockObj.getProductId());
                            productAttr.setMessage(scenicProductEsDTO.getCancelPolicy()==1? ScenicProductConstants.TIME_CANCEL : ScenicProductConstants.NOBACK_NOCANCEL);
                            //成本乘以倍数，加上服务费，加上加服
                            BigDecimal rate = specStockObj.getCostPrice();
                            //汇率
                            Double price = scenicProductEsDTO.getExchangeRate();
                            BigDecimal mone = rate.multiply(BigDecimal.valueOf(price));
                            if (scenicProductEsDTO.getAmount() != null){
                                //成本+加服务费，等于售价，进1，
                                BigDecimal moneAttr = mone.add(scenicProductEsDTO.getAmount()).setScale(0,BigDecimal.ROUND_UP);
                                productAttr.setExchangeRateMoney(moneAttr);
                                productAttr.setMoney(moneAttr
                                        .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                            }else if (scenicProductEsDTO.getAmount() == null){
                                productAttr.setExchangeRateMoney(mone.setScale(0,BigDecimal.ROUND_UP));
                                productAttr.setMoney(mone.setScale(0,BigDecimal.ROUND_UP)
                                        .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                            }
                            productAttr.setPrice(specStockObj.getCostPrice());
                            productAttr.setId(scenicProductEsDTO.getAttrId());
                            productAttr.setTitle(scenicProductEsDTO.getAttr1Name());
                            productAttr.setAttrId(specStockObj.getId());
                            productAttr.setStockNumber(specStockObj.getStockNumber());

                            productAttrDTOS.add(productAttr);


                        scenicProductAttrListDTO.setItemList(productAttrDTOS);
                        scenicProductAttrListDTOS.add(scenicProductAttrListDTO);

                        /*productAttrDTO.setId(scenicProductEsDTO.getAttrId());
                        productAttrDTO.setTitle(scenicProductEsDTO.getAttr1Name());
                        productAttrDTO.setPrice(scenicProductEsDTO.getCostPrice());
                        productAttrDTO.setMoney(scenicProductEsDTO.getCostPrice().setScale(0,BigDecimal.ROUND_UP)
                                .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                        productAttrDTO.setMessage(scenicProductEsDTO.getCancelPolicy()==1? ScenicProductConstants.TIME_CANCEL : ScenicProductConstants.NOBACK_NOCANCEL);
                        productAttrDTOS.add(productAttrDTO);
                        scenicProductAttrListDTO.setItemList(productAttrDTOS);
                        scenicProductAttrListDTOS.add(scenicProductAttrListDTO);*/
                    }else{
                        boolean have = false;

                        for (ScenicProductAttrListDTO productAttrListDTO : scenicProductAttrListDTOS) {
                            if(productAttrListDTO.getTitle() != null && productAttrListDTO.getTitle().equals(attr2Name)){
                                have = true;
                                productAttrDTOS = productAttrListDTO.getItemList();
                                productAttrDTO.setTitle(scenicProductEsDTO.getAttr1Name());
                                productAttrDTO.setPrice(scenicProductEsDTO.getCostPrice());
                                productAttrDTO.setMessage(scenicProductEsDTO.getCancelPolicy()==1? ScenicProductConstants.TIME_CANCEL : ScenicProductConstants.NOBACK_NOCANCEL);
                                productAttrDTOS.add(productAttrDTO);
                                scenicProductAttrListDTO.setItemList(productAttrDTOS);
                                break;
                            }
                        }

                        if(!have){
                            productAttrDTO.setTitle(scenicProductEsDTO.getAttr1Name());
                            productAttrDTO.setPrice(scenicProductEsDTO.getCostPrice());
                            productAttrDTO.setMessage(scenicProductEsDTO.getCancelPolicy()==1? ScenicProductConstants.TIME_CANCEL : ScenicProductConstants.NOBACK_NOCANCEL);
                            productAttrDTOS.add(productAttrDTO);
                            scenicProductAttrListDTO.setItemList(productAttrDTOS);
                        }
                    }
                }

                scenicProductEsDetailDTO.setTripId(scenicProductEsDTO.getProductId());
                scenicProductEsDetailDTO.setTitle(scenicProductEsDTO.getProductName());
                scenicProductEsDetailDTO.setTheme("门票");
                {// 解析图片列表
                    String photosJson = scenicProductEsDTO.getPhotosJson();
                    if(photosJson != null){
                        List<PhotosJsonDTO> photosJsonDTOS = JSON.parseArray(photosJson, PhotosJsonDTO.class);
                        List<MediaListDTO> mediaListDTOS = new ArrayList<>();
                        for (PhotosJsonDTO photosJsonDTO : photosJsonDTOS) {
                            // 存在文件
                            if(photosJsonDTO.getUrl() != null && !photosJsonDTO.getUrl().trim().equals("")){
                                MediaListDTO mediaListDTO = new MediaListDTO();
                                String substring = photosJsonDTO.getUrl().substring(photosJsonDTO.getUrl().lastIndexOf(".")).toLowerCase();
                                mediaListDTO.setType(videoTypes.indexOf(substring)!=-1?1:2);
                                mediaListDTO.setNum(photosJsonDTO.getId());
                                mediaListDTO.setUrl(photosJsonDTO.getUrl());
                                mediaListDTOS.add(mediaListDTO);
                            }

                        }
                        scenicProductEsDetailDTO.setMediaList(mediaListDTOS);
                    }
                }
                {// 解析主题列表
                    String themeJson = scenicProductEsDTO.getThemeJson();
                    if(themeJson != null && !themeJson.trim().equals("")){
                        List<String> themes = JSON.parseArray(themeJson, String.class);
                        List<TagListDTO> tagListDTOS = new ArrayList<>();
                        for (String theme : themes) {
                            TagListDTO tagListDTO = new TagListDTO();
                            tagListDTO.setName(theme);
                            tagListDTOS.add(tagListDTO);
                        }
                        scenicProductEsDetailDTO.setTagList(tagListDTOS);
                    }
                }
                scenicProductEsDetailDTO.setNeedInfo(scenicProductEsDTO.getNeedInfo());
                scenicProductEsDetailDTO.setReserveCharge(scenicProductEsDTO.getReserveCharge());
            }
            {// 添加其它信息
                List<DocumentListDTO> documentListDTOS = new ArrayList<>();

                DocumentListDTO documentListDTO = new DocumentListDTO();
                documentListDTO.setTitle("产品介绍");
                documentListDTO.setContent(productIntroduces);
                documentListDTOS.add(documentListDTO);

                DocumentListDTO documentListDTO2 = new DocumentListDTO();
                documentListDTO2.setTitle("入场须知");
                documentListDTO2.setContent(admissionNotes);
                documentListDTOS.add(documentListDTO2);

                scenicProductEsDetailDTO.setDocumentList(documentListDTOS);
            }
            scenicProductEsDetailDTO.setTicketList(scenicProductAttrListDTOS);
        } catch (IOException e) {
            e.printStackTrace();
            scenicProductEsDetailDTO.setTicketList(new ArrayList<>());
        }
        // 添加足迹
        addUserFootPoint(scenicProductEsDetailDTO,productId,userId);
        return scenicProductEsDetailDTO;
    }

    /**
     * 查询门票详情ES
     * @param channelId
     * @param productId
     * @param userId
     * @return
     */
    @Override
    public ScenicProductEsDetailDTO selectScenicDetailEs(Long channelId, Long productId, Long userId) {
        ScenicProductEsDetailDTO scenicProductEsDetailDTO = new ScenicProductEsDetailDTO();
        SearchRequest searchRequest = new SearchRequest(ElasticSearchConstant.SCENIC);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        Long channelIdAttr = channelId;
        {// 过滤条件
            if(channelId != null){
                if (!channelId.equals(ChannelMainData.APP_H5.getId())) {
                    channelIdAttr = channelId;
                    channelId = ChannelMainData.APP_H5.getId();
                }
                boolQueryBuilder.filter( QueryBuilders.fuzzyQuery("channelId", String.valueOf(channelId)) );
            }
            boolQueryBuilder.filter( QueryBuilders.fuzzyQuery("productId", String.valueOf(productId)) );
        }
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = search.getHits();
            List<ScenicProductEsDTO> scenicProductEsDTOS = new ArrayList<>();
            List<ScenicProductAttrListDTO> scenicProductAttrListDTOS = new ArrayList<>();

            // 产品描述
            String productIntroduces = "";
            // 入场须知
            String admissionNotes = "";
            //预订须知
            String customerNotice = "";

            for (SearchHit hit : hits) {
                ScenicProductEsDTO scenicProductEsDTO = JSON.parseObject(hit.getSourceAsString(), ScenicProductEsDTO.class);
                    ScenicProductChannelOnlineSelfPlatformDTO platformObj = new ScenicProductChannelOnlineSelfPlatformDTO();
                    //计算总价
                    //BigDecimal price = null;
                    //成本乘以倍数，加上服务费，加上加服
                    List<ScenicProductCostStrategySpecStock> stocksObj = scenicProductCostStrategySpecStockMapper.quertCostPriceByid(scenicProductEsDTO.getProductId());
                    if (!Objects.isNull(stocksObj.get(0).getCostPrice())){
                        //成本
                        scenicProductEsDTO.setCostPrice(stocksObj.get(0).getCostPrice());
                    }
                if (null != channelIdAttr){
                    platformObj = scenicProductChannelOnlineSelfPlatformMapper.selectByProductId( productId , channelIdAttr);
                    if (!Objects.isNull(platformObj)){
                        //加服价格
                        scenicProductEsDTO.setAmount(platformObj.getAmount());
                    }
                }
                // 计算价格
                computeScenicPriceScenicDetail(scenicProductEsDTO);
                // 设置价格
                scenicProductEsDetailDTO.setPrice(scenicProductEsDTO.getCostPrice());
                // 设置总价
                scenicProductEsDetailDTO.setMoney(scenicProductEsDTO.getCostPrice());

                // 设置使用有效期
                scenicProductEsDetailDTO.setValidDay(scenicProductEsDTO.getValidDay());
                // 设置使用有效期类型
                scenicProductEsDetailDTO.setValidType(scenicProductEsDTO.getValidType());
                // 设置使用有效期
                scenicProductEsDetailDTO.setValidDayBegin(scenicProductEsDTO.getValidDayBegin());
                // 设置使用有效期
                scenicProductEsDetailDTO.setValidDayEnd(scenicProductEsDTO.getValidDayEnd());
                // 设置位置信息
                scenicProductEsDetailDTO.setScenicLocation(scenicProductEsDTO.getScenicLocation());
                scenicProductEsDetailDTO.setScenicPhotoJson(scenicProductEsDTO.getScenicPhotoJson());

                //获取scenicLocation景点地址
                scenicProductEsDetailDTO.setCoverPhoto(scenicProductEsDTO.getCoverImage());

                scenicProductEsDetailDTO.setLat(scenicProductEsDTO.getLat());
                scenicProductEsDetailDTO.setLon(scenicProductEsDTO.getLon());
                // 设置入园须知
                scenicProductEsDetailDTO.setAdmissionNotes(scenicProductEsDTO.getAdmissionNotes());
                scenicProductEsDetailDTO.setCityId(scenicProductEsDTO.getCityId());

                scenicProductEsDTOS.add(scenicProductEsDTO);
                productIntroduces = scenicProductEsDTO.getProductIntroduces();
                admissionNotes = scenicProductEsDTO.getAdmissionNotes();
                if (StringUtils.isBlank(admissionNotes)){

                    if (StringUtils.isNotBlank(String.valueOf(scenicProductEsDTO.getScenicId()))){
                        ScenicDTO scenicObj = iSceneService.quertByiId(String.valueOf(scenicProductEsDTO.getScenicId()));
                        admissionNotes = scenicObj.getAdmissionNotes();
                    }
                }
                if (StringUtils.isNotBlank(String.valueOf(scenicProductEsDTO.getProductId()))){
                    ScenicResourceDetailDTO scenicResourceDetailObj = iScenicResourceService.quertByProductId(String.valueOf(scenicProductEsDTO.getProductId()));
                    if (!Objects.isNull(scenicResourceDetailObj)){
                        customerNotice = scenicResourceDetailObj.getCustomerNotice();
                    }
                }

                {
                    String attr2Name = scenicProductEsDTO.getAttr2Name()!=null?scenicProductEsDTO.getAttr2Name():"default";

                    ScenicProductAttrListDTO scenicProductAttrListDTO = new ScenicProductAttrListDTO();
                    scenicProductAttrListDTO.setId(scenicProductEsDTO.getProductId());
                    scenicProductAttrListDTO.setTitle(attr2Name);
                    List<ProductAttrDTO> productAttrDTOS = new ArrayList<>();



                    /*List<ScenicSpecStockDTO> scenicSpecStockList = new ArrayList<>();
                    List<ScenicProductCostStrategySpecStock>  scenicProductCostStrategySpecStock = scenicProductCostStrategySpecStockMapper.quertByid(productId);
                    for (ScenicProductCostStrategySpecStock specStockObj : scenicProductCostStrategySpecStock){
                        ScenicSpecStockDTO scenicSpecStockObj = new ScenicSpecStockDTO();
                        //门票及价格列表
                        scenicSpecStockObj.setAttr1Name(specStockObj.getAttr1Name());
                        scenicSpecStockObj.setAttr2Name(specStockObj.getAttr2Name());
                        scenicSpecStockObj.setId(specStockObj.getId());
                        scenicSpecStockObj.setStrategyId(specStockObj.getStrategyId());
                        scenicSpecStockObj.setProductId(specStockObj.getProductId());
                        scenicSpecStockObj.setCostPrice(specStockObj.getCostPrice());
                        scenicSpecStockObj.setMessage(scenicProductEsDTO.getCancelPolicy()==1? ScenicProductConstants.TIME_CANCEL : ScenicProductConstants.NOBACK_NOCANCEL);
                        //成本乘以倍数，加上服务费，加上加服
                        BigDecimal rate = specStockObj.getCostPrice();
                        Double price = scenicProductEsDTO.getExchangeRate();
                        BigDecimal mone = rate.multiply(BigDecimal.valueOf(price));
                        if (scenicProductEsDTO.getAmount() != null){
                            scenicSpecStockObj.setMoney(mone.setScale(0,BigDecimal.ROUND_UP)
                                    .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP))
                                    .add(scenicProductEsDTO.getAmount().setScale(0,BigDecimal.ROUND_UP)));
                        }else if (scenicProductEsDTO.getAmount() == null){
                            scenicSpecStockObj.setMoney(mone.setScale(0,BigDecimal.ROUND_UP)
                                    .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                        }
                        scenicSpecStockList.add(scenicSpecStockObj);
                        scenicProductAttrListDTO.setItemList(scenicSpecStockList);
                    }
                    scenicProductAttrListDTOS.add(scenicProductAttrListDTO);*/


                    // 门票信息
                    ProductAttrDTO productAttrDTO = new ProductAttrDTO();
                    if(scenicProductAttrListDTOS.size() == 0){
                        List<ScenicProductCostStrategySpecStock>  scenicProductCostStrategySpecStock = scenicProductCostStrategySpecStockMapper.quertByid(productId);
                        for (ScenicProductCostStrategySpecStock specStockObj : scenicProductCostStrategySpecStock){
                            ProductAttrDTO productAttr = new ProductAttrDTO();
                            //门票及价格列表
                            productAttr.setAttr1Name(specStockObj.getAttr1Name());
                            productAttr.setAttr2Name(specStockObj.getAttr2Name());
                            productAttr.setId(scenicProductEsDTO.getAttrId());
                            productAttr.setStrategyId(specStockObj.getStrategyId());
                            productAttr.setProductId(specStockObj.getProductId());
                            productAttr.setMessage(scenicProductEsDTO.getCancelPolicy()==1? ScenicProductConstants.TIME_CANCEL : ScenicProductConstants.NOBACK_NOCANCEL);
                            //成本乘以倍数，加上服务费，加上加服
                            BigDecimal rate = specStockObj.getCostPrice();
                            //汇率
                            Double price = scenicProductEsDTO.getExchangeRate();
                            BigDecimal mone = rate.multiply(BigDecimal.valueOf(price));
                            if (scenicProductEsDTO.getAmount() != null){
                                //成本+加服务费，等于售价，进1，
                                BigDecimal moneAttr = mone.add(scenicProductEsDTO.getAmount()).setScale(0,BigDecimal.ROUND_UP);
                                productAttr.setMoney(moneAttr
                                        .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                            }else if (scenicProductEsDTO.getAmount() == null){
                                productAttr.setMoney(mone.setScale(0,BigDecimal.ROUND_UP)
                                        .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                            }
                            productAttr.setPrice(specStockObj.getCostPrice());
                            productAttr.setId(scenicProductEsDTO.getAttrId());
                            productAttr.setTitle(scenicProductEsDTO.getAttr1Name());
                            productAttr.setAttrId(specStockObj.getId());
                            productAttr.setStockNumber(specStockObj.getStockNumber());
                            productAttrDTOS.add(productAttr);
                        }

                        scenicProductAttrListDTO.setItemList(productAttrDTOS);
                        scenicProductAttrListDTOS.add(scenicProductAttrListDTO);

                        /*productAttrDTO.setId(scenicProductEsDTO.getAttrId());
                        productAttrDTO.setTitle(scenicProductEsDTO.getAttr1Name());
                        productAttrDTO.setPrice(scenicProductEsDTO.getCostPrice());
                        productAttrDTO.setMoney(scenicProductEsDTO.getCostPrice().setScale(0,BigDecimal.ROUND_UP)
                                .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                        productAttrDTO.setMessage(scenicProductEsDTO.getCancelPolicy()==1? ScenicProductConstants.TIME_CANCEL : ScenicProductConstants.NOBACK_NOCANCEL);
                        productAttrDTOS.add(productAttrDTO);
                        scenicProductAttrListDTO.setItemList(productAttrDTOS);
                        scenicProductAttrListDTOS.add(scenicProductAttrListDTO);*/
                    }else{
                        boolean have = false;

                        for (ScenicProductAttrListDTO productAttrListDTO : scenicProductAttrListDTOS) {
                            if(productAttrListDTO.getTitle() != null && productAttrListDTO.getTitle().equals(attr2Name)){
                                have = true;
                                productAttrDTOS = productAttrListDTO.getItemList();
                                productAttrDTO.setTitle(scenicProductEsDTO.getAttr1Name());
                                productAttrDTO.setPrice(scenicProductEsDTO.getCostPrice());
                                productAttrDTO.setMessage(scenicProductEsDTO.getCancelPolicy()==1? ScenicProductConstants.TIME_CANCEL : ScenicProductConstants.NOBACK_NOCANCEL);
                                productAttrDTOS.add(productAttrDTO);
                                scenicProductAttrListDTO.setItemList(productAttrDTOS);
                                break;
                            }
                        }

                        if(!have){
                            productAttrDTO.setTitle(scenicProductEsDTO.getAttr1Name());
                            productAttrDTO.setPrice(scenicProductEsDTO.getCostPrice());
                            productAttrDTO.setMessage(scenicProductEsDTO.getCancelPolicy()==1? ScenicProductConstants.TIME_CANCEL : ScenicProductConstants.NOBACK_NOCANCEL);
                            productAttrDTOS.add(productAttrDTO);
                            scenicProductAttrListDTO.setItemList(productAttrDTOS);
                        }
                    }
                }

                scenicProductEsDetailDTO.setTripId(scenicProductEsDTO.getProductId());
                scenicProductEsDetailDTO.setTitle(scenicProductEsDTO.getProductName());
                scenicProductEsDetailDTO.setTheme("门票");
                {// 解析图片列表
                    String photosJson = scenicProductEsDTO.getPhotosJson();
                    if(photosJson != null){
                        List<PhotosJsonDTO> photosJsonDTOS = JSON.parseArray(photosJson, PhotosJsonDTO.class);
                        List<MediaListDTO> mediaListDTOS = new ArrayList<>();
                        for (PhotosJsonDTO photosJsonDTO : photosJsonDTOS) {
                            // 存在文件
                            if(photosJsonDTO.getUrl() != null && !photosJsonDTO.getUrl().trim().equals("")){
                                MediaListDTO mediaListDTO = new MediaListDTO();
                                String substring = photosJsonDTO.getUrl().substring(photosJsonDTO.getUrl().lastIndexOf(".")).toLowerCase();
                                mediaListDTO.setType(videoTypes.indexOf(substring)!=-1?1:2);
                                mediaListDTO.setNum(photosJsonDTO.getId());
                                mediaListDTO.setUrl(photosJsonDTO.getUrl());
                                mediaListDTOS.add(mediaListDTO);
                            }

                        }
                        scenicProductEsDetailDTO.setMediaList(mediaListDTOS);
                    }
                }
                {// 解析主题列表
                    String themeJson = scenicProductEsDTO.getThemeJson();
                    if(themeJson != null && !themeJson.trim().equals("")){
                        List<String> themes = JSON.parseArray(themeJson, String.class);
                        List<TagListDTO> tagListDTOS = new ArrayList<>();
                        for (String theme : themes) {
                            TagListDTO tagListDTO = new TagListDTO();
                            tagListDTO.setName(theme);
                            tagListDTOS.add(tagListDTO);
                        }
                        scenicProductEsDetailDTO.setTagList(tagListDTOS);
                    }
                }
                scenicProductEsDetailDTO.setNeedInfo(scenicProductEsDTO.getNeedInfo());
                scenicProductEsDetailDTO.setReserveCharge(scenicProductEsDTO.getReserveCharge());
            }
            {// 添加其它信息
                List<DocumentListDTO> documentListDTOS = new ArrayList<>();

                DocumentListDTO documentListDTO = new DocumentListDTO();
                documentListDTO.setTitle("产品介绍");
                documentListDTO.setContent(productIntroduces);
                documentListDTOS.add(documentListDTO);

                DocumentListDTO documentListDTO2 = new DocumentListDTO();
                documentListDTO2.setTitle("入场须知");
                documentListDTO2.setContent(admissionNotes);
                documentListDTOS.add(documentListDTO2);

                DocumentListDTO documentListObj = new DocumentListDTO();
                documentListObj.setTitle("预订须知");
                documentListObj.setContent(customerNotice);
                documentListDTOS.add(documentListObj);

                scenicProductEsDetailDTO.setDocumentList(documentListDTOS);
            }
            scenicProductEsDetailDTO.setTicketList(scenicProductAttrListDTOS);
        } catch (IOException e) {
            e.printStackTrace();
            scenicProductEsDetailDTO.setTicketList(new ArrayList<>());
        }
        // 添加足迹
        addUserFootPoint(scenicProductEsDetailDTO,productId,userId);
        return scenicProductEsDetailDTO;
    }

    @Override
    public List<ScenicProductEsDTO> selectScenicTicketListByProductId(Long channelId, Long productId) {
        SearchRequest searchRequest = new SearchRequest(ElasticSearchConstant.SCENIC);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.filter(QueryBuilders.matchQuery("channelId", channelId));
        boolQueryBuilder.filter(QueryBuilders.matchQuery("productId", productId));
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        try{
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = search.getHits();
            List<ScenicProductEsDTO> scenicProductEsDTOS = new ArrayList<>();
            for (SearchHit hit : hits) {
                if(hit.getSourceAsString() != null){
                    scenicProductEsDTOS.add(JSON.parseObject(hit.getSourceAsString(), ScenicProductEsDTO.class));
                }
            }
            return scenicProductEsDTOS;
        }catch (Exception e){
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public String initIndex() {
        String info = "";
        try{
            GetIndexRequest getIndexRequest = new GetIndexRequest(ElasticSearchConstant.SCENIC);
            boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
            if(exists){
                DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(ElasticSearchConstant.SCENIC);
                restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
            }
            // 重新创建索引
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(ElasticSearchConstant.SCENIC);

            Map<String, Object> mapping = new HashMap<>();
            Map<String, Object> properties = new HashMap<>();

            // 文本类型
            Map<String, Object> typeMap = new HashMap<>();
            typeMap.put("type", "keyword");
            // 时间类型
            Map<String, Object> timeMap = new HashMap<>();
            timeMap.put("type", "date");

            List<String> fields = new ArrayList<>();
            fields.add("id");

            // 渠道ID
            fields.add("channelId");
            // 渠道名称
            fields.add("channelName");
            // 策略ID
            fields.add("strategyId");
            // 策略名称
            fields.add("strategyName");
            // 产品ID
            fields.add("productId");
            // 产品名称
            fields.add("productName");
            // 是否推荐
            fields.add("isRecommend");
            // 城市ID
            fields.add("cityId");
            // 城市名称
            fields.add("cityName");
            // 产品描述
            fields.add("productIntroduces");
            // 主题JSON
            fields.add("themeJson");
            // 图片JSON
            fields.add("photosJson");
            // 预订服务费类型
            fields.add("reserveChargeType");
            // 预订服务费
            fields.add("reserveCharge");
            // 加幅类型
            fields.add("adjustType");
            // 加幅金额
            fields.add("amount");
            // 加幅百分比
            fields.add("precent");
            // 销售开始时间
            fields.add("saleTimeBegin");
            // 销售结束时间
            fields.add("saleTimeEnd");
            // 产品修改时间
            fields.add("gmtModified");
            // 上架状态
            fields.add("status");
            // 售卖状态
            fields.add("saleStatus");
            // 产品删除状态
            fields.add("isDeleted");
            // 产品成本价
            fields.add("costPrice");
            // 汇率
            fields.add("exchangeRate");
            // 门票类型
            fields.add("attr2Name");
            // 门票规格
            fields.add("attr1Name");
            // 已销售数量
            fields.add("soldStock");
            // 负责人ID
            fields.add("chargeUserId");
            // 负责人名称
            fields.add("chargeUser");
            // 供应商ID
            fields.add("supplierId");
            // 供应商名称
            fields.add("supplierName");
            // 是否需要填写联系人信息
            fields.add("needInfo");
            // 入园须知
            fields.add("admissionNotes");
            // 预订后是否可退
            fields.add("allowRefund");
            // 规格ID
            fields.add("attrId");
            // 有效期类型
            fields.add("validType");
            // 有效期起始
            fields.add("validDayBegin");
            // 有效期截至
            fields.add("validDayEnd");
            // 几日有效期
            fields.add("validDay");
            // 取消政策
            fields.add("cancelPolicy");

            for (String field : fields) {
                properties.put(field, JSON.parse(JSON.toJSONString(typeMap)));
            }

            mapping.put("properties", properties);
            createIndexRequest.mapping(JSON.toJSONString(mapping), XContentType.JSON);
            restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            info += "1. 增加成功\r\n";
            // 全量更新数据
            Result<List<ScenicProductEsDTO>> listResult = iScenicProductService.queryListByEs();
            info += "2. 查询到数据:" + listResult.getData().size() + "\r\n";
            if(listResult.isSuccess()){
                List<ScenicProductEsDTO> data = listResult.getData();
                for (ScenicProductEsDTO item : data) {
                    if(item.getScenicId() != null && !item.getScenicId().equals("")){
                        // 查询景点信息
                        Result<List<ScenicDTO>> listResult1 = iSceneService.quertByids(String.valueOf(item.getScenicId()));
                        if(listResult1.isSuccess()){
                            List<ScenicDTO> data1 = listResult1.getData();
                            if(data1 != null && data1.size() > 0){
                                ScenicDTO scenicDTO = data1.get(0);
                                // 地址
                                item.setScenicLocation(scenicDTO.getScenicLocation());
                                // 维度
                                item.setLat(scenicDTO.getLat());
                                // 经度
                                item.setLon(scenicDTO.getLon());
                                // 入园须知
                                item.setAdmissionNotes(scenicDTO.getAdmissionNotes());
                                // 封面图
                                item.setCoverImage(scenicDTO.getCoverPhoto());
                            }
                        }
                    }
                    IndexRequest indexRequest = new IndexRequest(ElasticSearchConstant.SCENIC);
                    indexRequest.id(String.valueOf(item.getProductId()));
                    indexRequest.source(JSON.toJSONString(item), XContentType.JSON);
                    try{
                        restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            info += "3. 更新失败\r\n";
        }
        info += "3. 更新成功\r\n";
        return info;
    }

    // 计算价格
    public void computeScenicPriceTicketList(ScenicProductEsDTO scenicProductEsDTO){
        if(scenicProductEsDTO != null){
            // 成本价
            BigDecimal costPrice = scenicProductEsDTO.getCostPrice();
            // 成本价计算汇率
            if(scenicProductEsDTO.getExchangeRate() != null){
                costPrice = costPrice.multiply(new BigDecimal(String.valueOf(scenicProductEsDTO.getExchangeRate())));
            }

            BigDecimal jfPrice = new BigDecimal("0");
            // 加幅类型
            Integer adjustType = scenicProductEsDTO.getAdjustType();
            if(adjustType != null){
                if(adjustType.equals(1)){
                    // 指定数值
                    if(scenicProductEsDTO.getAmount() != null){
                        jfPrice = jfPrice.add(scenicProductEsDTO.getAmount());
                    }
                }else if(adjustType.equals(2)){
                    // 百分比
                    if(scenicProductEsDTO.getAmount() != null){
                        jfPrice = jfPrice.add(costPrice.divide(scenicProductEsDTO.getAmount(), 0, BigDecimal.ROUND_UNNECESSARY).multiply(new BigDecimal("100")));
                    }
                }
            }

            // 计算预订服务费
            BigDecimal ydPrice = new BigDecimal("0");
            if(scenicProductEsDTO.getReserveChargeType() != null){
                if(scenicProductEsDTO.getReserveCharge() != null){
                    if(scenicProductEsDTO.getReserveChargeType().equals(1)){
                        // 数值
                        ydPrice = ydPrice.add(scenicProductEsDTO.getReserveCharge());
                    }else if(scenicProductEsDTO.getReserveChargeType().equals(2)){
                        // 百分比
                        ydPrice = ydPrice.add(costPrice.divide(scenicProductEsDTO.getReserveCharge(), 0, BigDecimal.ROUND_UNNECESSARY).multiply(new BigDecimal("100")));
                    }
                }
            }
            String logStr = ", 成本价:" + costPrice + ", 加幅:" + jfPrice + ", 预订:" + ydPrice;
            // 叠加 [ 已计算汇率的成本价+加幅 ]
            costPrice = costPrice.add(jfPrice);
            costPrice = costPrice.setScale(0,BigDecimal.ROUND_UP);
            costPrice = costPrice.add(ydPrice.setScale(0,BigDecimal.ROUND_UP));
            LOGGER.info("总价:" + costPrice + logStr);
            scenicProductEsDTO.setCostPrice(costPrice);
        }
    }

    // 计算价格
    public void computeScenicPriceScenicDetail(ScenicProductEsDTO scenicProductEsDTO){
        if(scenicProductEsDTO != null){
            // 成本价
            BigDecimal costPrice = scenicProductEsDTO.getCostPrice();
            // 成本价计算汇率
            if(scenicProductEsDTO.getExchangeRate() != null){
                costPrice = costPrice.multiply(new BigDecimal(String.valueOf(scenicProductEsDTO.getExchangeRate())));
            }

            BigDecimal jfPrice = new BigDecimal("0");
            // 加幅类型
            Integer adjustType = scenicProductEsDTO.getAdjustType();
            if(adjustType != null){
                if(adjustType.equals(1)){
                    // 指定数值
                    if(scenicProductEsDTO.getAmount() != null){
                        jfPrice = jfPrice.add(scenicProductEsDTO.getAmount());
                    }
                }else if(adjustType.equals(2)){
                    // 百分比
                    if(scenicProductEsDTO.getAmount() != null){
                        jfPrice = jfPrice.add(costPrice.divide(scenicProductEsDTO.getAmount(), 0, BigDecimal.ROUND_UNNECESSARY).multiply(new BigDecimal("100")));
                    }
                }
            }

            // 计算预订服务费
            BigDecimal ydPrice = new BigDecimal("0");
            if(scenicProductEsDTO.getReserveChargeType() != null){
                if(scenicProductEsDTO.getReserveCharge() != null){
                    if(scenicProductEsDTO.getReserveChargeType().equals(1)){
                        // 数值
                        ydPrice = ydPrice.add(scenicProductEsDTO.getReserveCharge());
                    }else if(scenicProductEsDTO.getReserveChargeType().equals(2)){
                        // 百分比
                        ydPrice = ydPrice.add(costPrice.divide(scenicProductEsDTO.getReserveCharge(), 0, BigDecimal.ROUND_UNNECESSARY).multiply(new BigDecimal("100")));
                    }
                }
            }
            String logStr = ", 成本价:" + costPrice + ", 加幅:" + jfPrice + ", 预订:" + ydPrice;
            // 叠加 [ 已计算汇率的成本价+加幅 ]
            costPrice = costPrice.add(jfPrice);
            costPrice = costPrice.setScale(0,BigDecimal.ROUND_UP);
            costPrice = costPrice.add(ydPrice.setScale(0,BigDecimal.ROUND_UP));
            LOGGER.info("总价:" + costPrice + logStr);
            scenicProductEsDTO.setCostPrice(costPrice);
        }
    }
    // 计算价格
    public void computeScenicPrice(ScenicProductEsDTO scenicProductEsDTO){
        if(scenicProductEsDTO != null){
            // 成本价
            BigDecimal costPrice = scenicProductEsDTO.getCostPrice();
            // 成本价计算汇率
            if(scenicProductEsDTO.getExchangeRate() != null){
                costPrice = costPrice.multiply(new BigDecimal(String.valueOf(scenicProductEsDTO.getExchangeRate())));
            }

            BigDecimal jfPrice = new BigDecimal("0");
            // 加幅类型
            Integer adjustType = scenicProductEsDTO.getAdjustType();
            if(adjustType != null){
                if(adjustType.equals(1)){
                    // 指定数值
                    if(scenicProductEsDTO.getAmount() != null){
                        jfPrice = jfPrice.add(scenicProductEsDTO.getAmount());
                    }
                }else if(adjustType.equals(2)){
                    // 百分比
                    if(scenicProductEsDTO.getAmount() != null){
                        jfPrice = jfPrice.add(costPrice.divide(scenicProductEsDTO.getAmount(), 0, BigDecimal.ROUND_UNNECESSARY).multiply(new BigDecimal("100")));
                    }
                }
            }

            // 计算预订服务费
            BigDecimal ydPrice = new BigDecimal("0");
            if(scenicProductEsDTO.getReserveChargeType() != null){
                if(scenicProductEsDTO.getReserveCharge() != null){
                    if(scenicProductEsDTO.getReserveChargeType().equals(1)){
                        // 数值
                        ydPrice = ydPrice.add(scenicProductEsDTO.getReserveCharge());
                    }else if(scenicProductEsDTO.getReserveChargeType().equals(2)){
                        // 百分比
                        ydPrice = ydPrice.add(costPrice.divide(scenicProductEsDTO.getReserveCharge(), 0, BigDecimal.ROUND_UNNECESSARY).multiply(new BigDecimal("100")));
                    }
                }
            }
            String logStr = ", 成本价:" + costPrice + ", 加幅:" + jfPrice + ", 预订:" + ydPrice;
            // 叠加 [ 已计算汇率的成本价+加幅 ]
            costPrice = costPrice.add(jfPrice);
            LOGGER.info("总价:" + costPrice + logStr);
            scenicProductEsDTO.setCostPrice(costPrice);
        }
    }

    // 添加足迹
    private void addUserFootPoint(ScenicProductEsDetailDTO details, Long detailId, Long userId) {
        try {
            if (userId != null && CollectionUtils.isNotEmpty(details.getTicketList())) {
                UserFootPointReq req = new UserFootPointReq();
                req.setUserId(userId);
                req.setType(SystemBusinessType.ATTRACTION_TICKET.getCode());
                req.setTitle(details.getTitle());
                req.setContent(details.getSubTitle());
                req.setCurrencyId(Currency.HKD.getCode());
                req.setCurrency(Currency.HKD.getCurrency());
                req.setPrice(details.getTicketList().get(0).getItemList().get(0).getPrice());
                if(CollectionUtils.isNotEmpty(details.getMediaList())) {
                    for (MediaListDTO mediaListDTO : details.getMediaList()) {
                        if(mediaListDTO.getType() == 2) {
                            req.setCoverUrl(mediaListDTO.getUrl());
                            break;
                        }
                    }
                }
                req.setDetailId(detailId);
                userFootPointService.add(req);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
